import socket
import threading


class ServerTalk(object):
    """
        1.启动服务端
        2.绑定地址和端口号
        3.监听客户端的连接请求
        4.收发消息
        5.关闭
    """

    def __init__(self):
        # {"用户名":socket,"用户名":socket,...,"用户名":socket}
        self.client_dct = {}

    def accept_client(self, port):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        address = ("127.0.0.1", port)
        server.bind(address)
        server.listen(10)
        print("服务器启动成功!欢迎大家来聊天!")

        while 1:
            client_socket, addr = server.accept()
            print(client_socket, addr)
            client_socket.send("欢迎来自{}的朋友,请输入你的姓名".format(str(addr)).encode("utf-8"))
            while 1:
                # 为了避免输入的姓名是重复的
                client_name = client_socket.recv(1024).decode("utf-8")
                if client_name in self.client_dct:
                    client_socket.send("用户名已经重复请重新输入".format(str(addr)).encode("utf-8"))
                else:
                    client_socket.send("欢迎名字是:{}的朋友加入群聊".format(client_name).encode("utf-8"))
                    self.client_dct[client_name] = client_socket
                    break

            # 通知所有人 有人加入群聊了
            for key, value in self.client_dct.items():
                value.send("欢迎{}加入群聊".format(client_name).encode("utf-8"))

            threading.Thread(target=self.send_receive, args=(client_name, client_socket, addr)).start()

    def send_receive(self, username, chanel, address):
        # try:
        while 1:
            from_msg = chanel.recv(1024).decode("utf-8")  # 接收来自于客户端的消息
            print("收到来自{}-{}的消息:{}".format(username, str(address), from_msg))

            # @朱 今天手机为啥没交上来!
            if str(from_msg).startswith("@"):  # 发给某个人
                msg_list = from_msg.split(" ")  # ["@人名","消息正文"]
                private_name = msg_list[0][1:].strip()  # 得到收件人的姓名
                print("private_name:{}".format(private_name))
                private_msg = msg_list[1]  # 得到私信的正文内容
                private_chanel = self.find_chanel(private_name)
                if private_chanel != None:
                    private_chanel.send("{}私聊你:{}".format(username, private_msg).encode("utf-8"))
                else:
                    chanel.send("你私聊的用户:{}不存在".format(private_name).encode("utf-8"))
            else:  # 发给所有人的
                for key, value in self.client_dct.items():
                    value.send("{}对所有人说:{}".format(username, from_msg).encode("utf-8"))

    # except:
    # print("服务器刷脾气了,罢工了!")

    def find_chanel(self, username):
        for key, value in self.client_dct.items():
            if key == username:
                return value
        else:
            return None


if __name__ == '__main__':
    ts = ServerTalk()
    ts.accept_client(9669)
